package com.tanhua.system.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.CommentApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.system.vo.CommentVo;
import com.tanhua.system.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @Author: zxw
 * @Description:
 * @Date: Created in 20:42 2021/1/17
 * @ModifiedBy:
 */

@Service
public class CommentsListService {

    @Reference(version = "1.0.0")
    private CommentApi commentApi;

    @Autowired
    private UserInfoService userInfoService;

    public PageResult queryCommentsList(Integer pageSize, Integer page,
                                        String sortProp, String sortOrder, Integer messageID) {

        PageResult pageResult = new PageResult();
        pageResult.setCounts(0); //总记录数
        pageResult.setPages(0); //总页数
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        // 从dubbo中获取comments对象
        PageInfo<Comment> pageInfo = this.commentApi.queryCommentsList(messageID, page, pageSize, sortProp, sortOrder);
        List<Comment> records = pageInfo.getRecords();
        // 判断是否为空
        if (CollectionUtils.isEmpty(records)) {
            return pageResult;
        }

        HashSet<Long> userIds = new HashSet<>();
        for (Comment record : records) {
            userIds.add(record.getUserId());
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        //填充CommentVo对象
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment record : records) {
            CommentVo commentVo = new CommentVo();
            commentVo.setId(record.getId().toHexString());//编号
            commentVo.setContent(record.getContent()); //评论人内容
            commentVo.setCreateDate(Math.toIntExact(record.getCreated())); // 评论时间

            for (UserInfo userInfo : userInfoList) {
                if (userInfo.getUserId().longValue() == record.getUserId().longValue()) {
                    commentVo.setNickname(userInfo.getNickName());//评论人昵称
                }
            }
            commentVoList.add(commentVo);
        }
        pageResult.setItems(commentVoList);
        return pageResult;
    }
}
